package org.example.util;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.extern.slf4j.Slf4j;
import org.example.model.LoginUser;

import java.util.Date;

@Slf4j
public class JWTUtil {
    /**
     * 主题
     */
    private static final String SUBJECT = "xdclass";
    /**
     * 加密密钥
     */
    private static final String SECRET = "secret";
    /**
     * 令牌前缀
     */
    private static final String TOKEN_PREFIX = "dcloud-link";
    /**
     * 过期时间7天
     */
    private static final long EXPIRRED = 1000 * 60 * 60 * 24 * 7;


    /**
     * 根据⽤户信息，⽣成令牌
     *
     * @param loginUser
     * @return
     */
    public static String geneJsonWebTokne(LoginUser loginUser) {
        if (loginUser == null) {
            throw new NullPointerException("对象为空");
        }

        String token = Jwts.builder().setSubject(SUBJECT)
                //配置payload
                .claim("head_img", loginUser.getHeadImg())
                .claim("account_no", loginUser.getAccountNo())
                .claim("username", loginUser.getUserName())
                .claim("mail", loginUser.getMail())
                .claim("phone", loginUser.getPhone())
                .claim("auth", loginUser.getAuth())
                .setIssuedAt(new Date())
                .setExpiration(new Date(CommonUtil.getCurrentTimestamp() + EXPIRRED))
                .signWith(SignatureAlgorithm.HS256, SECRET).compact();
        token = TOKEN_PREFIX + token;
        return token;
    }

    /**
     * 校验token的⽅法
     *
     * @param token
     * @return
     */
    public static Claims checkJWT(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token.replace(TOKEN_PREFIX, ""))
                    .getBody();
            return claims;
        } catch (ExpiredJwtException e) {
            log.error("JWT 解密失败：{}",e);
            return null;
        }
    }
}
